package com.wingsboat.common.protect.lockProcessor.impl;

import com.wingsboat.common.protect.aspect.AthenaLockAspect;
import com.wingsboat.common.protect.lockProcessor.AthenaLockProcessor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author wangzhong
 * @description: 分布式锁处理器
 * @date 2024/7/19 16:01
 */
@Component
public class RedissionLockProcessor implements AthenaLockProcessor, InitializingBean {

    @Autowired
    private AthenaLockAspect athenaLockAspect;

    @Resource
    private RedissonClient redissonClient;
    /**
     * 处理
     * @param joinPoint
     * @param key
     * @param leaseTime
     * @return
     * @throws Throwable
     */
    @Override
    public Object proceed(ProceedingJoinPoint joinPoint, String key, long leaseTime) throws Throwable {
        RLock lock = null;
        try {
            lock = redissonClient.getLock(key);
            if (leaseTime > 0) {
                lock.lock(leaseTime, TimeUnit.MILLISECONDS);
            } else {
                lock.lock();
            }

            return joinPoint.proceed();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (lock != null && lock.isLocked()) {
                lock.unlock();
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        athenaLockAspect.addAthenaLockProcessor(this);
    }
}
